package main

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"os"
	"path"
	"strings"
)

func getManifest(snm string) ([]byte, error) {

	snm = path.Base(snm)
	snm = strings.TrimRight(strings.TrimLeft(snm, "lib"), ".so")

	buf := new(bytes.Buffer)
	buf.WriteString(`<?xml version="1.0" encoding="utf-8"?>`)
	err := manifestTmpl.Execute(buf, manifestTmplData{
		// TODO(crawshaw): a better package path.
		JavaPkgPath: "org.golang." + snm,
		Name:        strings.Title(snm),
		LibName:     snm,
	})

	if err != nil {
		return nil, err
	}

	manifestData := buf.Bytes()
	fmt.Fprintf(os.Stderr, "generated AndroidManifest.xml:\n%s\n", manifestData)

	/**/
	ins := bytes.NewBuffer(manifestData)
	kk, err := binaryXML(ins)
	if err != nil {
		return nil, err
	}

	/**/
	return kk, nil
}

func tryPack(args []string) error {

	if len(args) < 1 {
		return fmt.Errorf("args, need so file name")
	}

	fmt.Printf("open, %s\n", args[0])
	so, err := os.Open(args[0])
	if err != nil {
		return err
	}

	defer so.Close()

	/**/
	buildO := androidPkgName("test_basic") + ".apk"
	fout, err := os.Create(buildO)
	if err != nil {
		return err
	}

	defer fout.Close()

	/**/
	zk := NewApkWriter(fout)
	defer zk.Close()

	maniData, err := getManifest(args[0])
	if err != nil {
		return err
	}

	/* AndroidManifest.xml */
	if err = zk.AddFromBytes("AndroidManifest.xml", maniData); err != nil {
		return err
	}

	/**/
	dexData, err := base64.StdEncoding.DecodeString(dexStr)
	if err != nil {
		return fmt.Errorf("internal error bad dexStr: %v", err)
	}

	/* classes.dex */
	if err = zk.AddFromBytes("classes.dex", dexData); err != nil {
		return err
	}

	/* libxxx.so */
	if err = zk.AddFromFile("lib/arm64-v8a/"+path.Base(args[0]), so); err != nil {
		return err
	}

	return nil
}
